//引入模块
let express = require('express');
let fs = require('fs');
let router = express.Router();
router.use(express.urlencoded({ extended: true }));
router.get('/login', (req, res) => {
    let loginList = fs.readFileSync('./login.html', 'utf-8');
    res.send(loginList);
});
router.get('/register', (req, res) => {
    let registerList = fs.readFileSync('./register.html', 'utf-8');
    res.send(registerList);
});
router.post('/doregister', (req, res) => {
    //防止输入空字段
    if (req.body.username == "" || req.body.password == "") {
        res.send("请输入用户名或者密码");
        return;
    }
    //读取person.json文件
    let data = fs.readFileSync("./persons.json", "utf-8");
    //把字符串转化为数组
    let arr = JSON.parse(data);
    let index = arr.findIndex((item) =>
        item.username == req.body.username && item.password == req.body.password
    );
    if (index == -1) {
        arr.push(req.body);
        fs.writeFileSync("./persons.json", JSON.stringify(arr));
        res.send("注册成功");
    } else {
        res.send("用户名已注册");
    }
});
router.post('/dologin', (req, res) => {
    //防止输入空字段
    if (req.body.username == "" || req.body.password == "") {
        res.send("请输入用户名或者密码");
        return;
    }
    //读取person.json文件
    let data = fs.readFileSync("./persons.json", "utf-8");
    //把字符串转化为数组
    let arr = JSON.parse(data);
    let index = arr.findIndex((item) =>
        item.username == req.body.username && item.password == req.body.password
    );
    if (index == -1) {
        res.send("账号或密码错误");
    } else {
        res.send("登陆成功");
    }
});
//暴露
module.exports = router;